package com.example.chapter05;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter05.database.UserDBHelper;
import com.example.chapter05.entity.User;
import com.example.chapter05.util.ViewUtil;

import java.util.List;
import java.util.Random;

public class LoginMainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private TextView tv_password;
    private EditText et_password;
    private CheckBox ck_remember;
    private Button btn_forget_password;
    private EditText et_phone;
    private RadioButton rb_password;
    private RadioButton rb_verifyCode;
    private ActivityResultLauncher<Intent> register;

    private String mPassword = "111111";
    private String mVerifyCode = null;
    private SharedPreferences userInfo;
    private UserDBHelper mHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_main);
        RadioGroup rg_login = findViewById(R.id.rg_login);

        tv_password = findViewById(R.id.tv_password);

        ck_remember = findViewById(R.id.ck_remember);
        btn_forget_password = findViewById(R.id.btn_forget_password);

        et_phone = findViewById(R.id.et_phone);
        et_password = findViewById(R.id.et_password);

        rb_password = findViewById(R.id.rb_password);
        rb_verifyCode = findViewById(R.id.rb_verifyCode);

        Button btn_login = findViewById(R.id.btn_login);
        btn_login.setOnClickListener(this);

        findViewById(R.id.btn_register).setOnClickListener(this);

        //给et_phone添加文本变更监听器
        et_phone.addTextChangedListener(new HideTextWatcher(et_phone, 11));
        et_password.addTextChangedListener(new HideTextWatcher(et_password, 6));

        //给btn_forget_password设置点击事件
        btn_forget_password.setOnClickListener(this);

        /*SharedPreferences主要存放一些初始化配置文件，比如上次输入的账号，密码等*/
        userInfo = getSharedPreferences("user_info", Context.MODE_PRIVATE);
        reload();




        //给rg_login设置单选监听器
        rg_login.setOnCheckedChangeListener(this);

        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                o -> {
                    if (o != null) {
                        Intent intent = o.getData();
                        if (intent != null && o.getResultCode() == Activity.RESULT_OK) {
                            Bundle bundle = intent.getExtras();
                            assert bundle != null;
                            mPassword = bundle.getString("newPassword");
                        }
                    }
                });




    }

    @Override
    protected void onStart() {
        super.onStart();
        mHelper = UserDBHelper.getInstance(this);
        mHelper.openReadLink();
        mHelper.openWriteLink();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //mHelper.closeLink();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHelper.closeLink();
    }


    private void reload() {
        boolean isRemember = userInfo.getBoolean("isRemember", false);
        if (isRemember) {
            String phone = userInfo.getString("phone", null);
            String password = userInfo.getString("password", null);
            et_password.setText(password);
            et_phone.setText(phone);
            ck_remember.setChecked(true);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.rb_password) {
            //将几个控件的文本进行更改
            tv_password.setText(getString(R.string.login_password));
            et_password.setHint(getString(R.string.input_password));
            btn_forget_password.setText(getString(R.string.forget_password));
            //让checkBox可见
            ck_remember.setVisibility(View.VISIBLE);
        }
        //选择了验证码登录方式
        if (checkedId == R.id.rb_verifyCode) {
            //将几个控件的文本进行更改
            tv_password.setText(getString(R.string.verifyCode1));
            et_password.setHint(getString(R.string.input_verifyCode));
            btn_forget_password.setText(getString(R.string.get_verifyCode));
            //让checkBox不可见
            ck_remember.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        String phone = et_phone.getText().toString();
        String password = et_password.getText().toString();

        if (phone.length() < 11) {
            Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (v.getId() == R.id.btn_forget_password) {
            //选择了密码方式校验，此时要跳到找回密码页面
            if (rb_password.isChecked()) {
                //以下携带手机号码跳转到找回密码页面
                Intent intent = new Intent(this, LoginForgetActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("phone", phone);
                bundle.putString("password", mPassword);
                //intent.putExtra("phone", phone);
                intent.putExtras(bundle);
                register.launch(intent);
            } else if (rb_verifyCode.isChecked()) {
                //生成一个六位随机数字的验证码
                mVerifyCode = String.format("%06d", new Random().nextInt(999999));
                //以下弹出提醒对话框，提醒用户记住六位验证码数字
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请记住验证码");
                builder.setMessage("手机号：" + phone + "," + "本次验证码是：" + mVerifyCode + ",请输入验证码");
                builder.setPositiveButton("好的", null);
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        }

        if (v.getId() == R.id.btn_login) {
            //密码校验
            if (rb_password.isChecked()) {
                //先去数据库查出当前的手机号是否存在
                List<User> list = mHelper.queryByPhone(phone);
                if(!list.isEmpty()){
                    //当前手机号存在，在比较密码
                    String exist_password = list.get(0).getPassword();
                    if (!exist_password.equals(et_password.getText().toString())) {
                        Toast.makeText(this, "请输入正确的密码", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                //如果此时记住密码被选，把手机号和密码存到sharePreferences
                /*if (ck_remember.isChecked()) {
                    SharedPreferences.Editor editor = userInfo.edit();
                    editor.putString("phone", phone);
                    editor.putString("password", mPassword);
                    editor.putBoolean("isRemember", ck_remember.isChecked());
                    editor.apply();
                }*/

                //如果此时记住密码被选，把手机号和密码存到数据库中，并更改配置信息
                if(ck_remember.isChecked()){
                    //更改配置信息
                    SharedPreferences.Editor editor = userInfo.edit();
                    editor.putString("phone", phone);
                    editor.putString("password",password );
                    editor.putBoolean("isRemember", ck_remember.isChecked());
                    editor.apply();

                    User user = new User();
                    user.setPassword(et_password.getText().toString());
                    user.setPhone(et_phone.getText().toString());
                    if(mHelper.insert(user) > 0){
                        Log.d("liu","插入成功");
                    }
                }
                //提示用户登录成功
                loginSuccess();
            } else if (rb_verifyCode.isChecked()) {
                //如果还没有点击获取验证码，此时点击了登录
                if (mVerifyCode == null) {
                    Toast.makeText(this, "当前没有获取验证码，请先点击获取验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                //验证码方式校验
                if (!mVerifyCode.equals(et_password.getText().toString())) {
                    Toast.makeText(this, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                //提示用户登录成功
                loginSuccess();
            }
        }

        if(v.getId() == R.id.btn_register){
            Intent intent = new Intent(this, RegisterActivity.class);
            startActivity(intent);
        }

    }

    private void loginSuccess() {
        String desc = String.format("您的手机号码是%s,恭喜你通过登录验证，点击‘确定’按钮返回上个页面",
                et_phone.getText().toString());
        //以下弹出提醒对话框，提示用户登录成功
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("登录成功");
        builder.setMessage(desc);
        builder.setPositiveButton("确定返回", (dialog, which) -> {
            //结束当前的活动页面
            finish();
        });

        builder.setNegativeButton("我再看看", null);
        builder.create().show();
    }

    private class HideTextWatcher implements TextWatcher {
        private final EditText mView;
        private final int mMaxLength;

        public HideTextWatcher(EditText etPhone, int maxLength) {
            this.mMaxLength = maxLength;
            this.mView = etPhone;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().length() == mMaxLength) {
                //隐藏输入法软键盘
                ViewUtil.hideOneInputMethod(LoginMainActivity.this, mView);
            }
        }
    }
}